import QtQuick
import QtQuick.Window
import QtQuick.Controls.Fusion
import QtQuick.Effects
import "qrc:/component/ZGlobal.js" as Global
import "qrc:/pages" as Pages
import "qrc:/component" as C

Window {
id: root
width: 1920
height: 1080
visible: true
title: qsTr("LEPURE")
flags: Qt.FramelessWindowHint | Qt.Window

property string cmd: collectionInfo.cmd
property bool   buzzing: false
onCmdChanged: {
    if (collectionInfo.cmd === 10 || collectionInfo.cmd === 11){  // OpenSerial=10  SetGPIO=11
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>");
        infoPage.item.msg=collectionInfo.info;
        infoPage.item.visible=true;
    }
    if (collectionInfo.cmd===12){   // Emergency=12
        emergencyPage.item.visible=true;
        collectionInfo.setBuzzing(true);
        buzzing=true;
    }

    if (collectionInfo.cmd===13){  //EmergencyClear=13
        emergencyPage.item.visible=false;
        collectionInfo.setBuzzing(false);
        buzzing=false;
    }
}

FontLoader {
    id: iconFont
    source: "qrc:/assets/fontawesome-free-6.7.2-desktop/otfs/Font Awesome 6 Free-Solid-900.otf"
}

Pages.Theme { id: theme }

    Rectangle {
        anchors.fill: parent

        gradient: Gradient {
            GradientStop { position: 0.0; color: (currentPage === "main" || currentPage === "ph" || currentPage === "conductivity") ? "#D2E6F6" : "#E6F0FB" }
            GradientStop { position: 1.0; color: (currentPage === "main" || currentPage === "ph" || currentPage === "conductivity") ? "#AFCCED" : "#E6F0FB" }
        }

        Canvas {
            anchors.fill: parent
            visible: (currentPage === "main" || currentPage === "ph" || currentPage === "conductivity")
            onPaint: {
                var ctx = getContext("2d");
                ctx.clearRect(0, 0, width, height);

            ctx.strokeStyle = "white";
            ctx.lineWidth = 0.5;

            var vanishingPointX = width / 2;
            var rows = 15;
            var cols = 6;

            for (var i = 0; i <= rows; i++) {
                var t = i / rows;
                var y = height * (1 - t);
                var alpha = 0.4 * (1 - t) * (1 - t);
                if (alpha < 0.02) continue;
                ctx.globalAlpha = alpha;
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(width, y);
                ctx.stroke();
            }

            var endY = height * -0.3;
            var alphaStart = 0.3;
            for (var j = 0; j <= cols; j++) {
                var h = j / cols;
                var xLeft = (width / 2) * h;
                var xRight = width - (width / 2) * h;

                ctx.globalAlpha = alphaStart;
                ctx.beginPath();
                ctx.moveTo(xLeft, height);
                ctx.lineTo(vanishingPointX, endY);
                ctx.stroke();

                ctx.beginPath();
                ctx.moveTo(xRight, height);
                ctx.lineTo(vanishingPointX, endY);
                ctx.stroke();
            }

            ctx.globalAlpha = 1.0;
        }
    }
}

Rectangle {
    id: header
    width: parent.width
    height: 70
    color: theme.secondaryColor
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right

    // 允许拖动
    DragHandler {
        target: null
        onActiveChanged: if (active) root.startSystemMove()
    }

    Image {
        source: "qrc:/assets/logo@2x.png"
        width: 140
        height: 65
        fillMode: Image.PreserveAspectFit
        anchors.verticalCenter: parent.verticalCenter
        anchors.left: parent.left
        anchors.leftMargin: 70
    }

    Rectangle {
        id: headerLine
        width: parent.width * 0.25
        height: header.height * 0.6
        color: Qt.lighter(theme.secondaryColor, 1.4)
        radius: 30
        anchors.verticalCenter: parent.verticalCenter
        anchors.left: parent.left
        anchors.leftMargin: 240
        Text {
            text: "批号："
            color: Qt.darker(theme.textColor, 1.2)
            font.pixelSize: 18
            anchors.verticalCenter: parent.verticalCenter
            anchors.left: parent.left
            anchors.leftMargin: 15
        }
        TextInput{
            anchors.fill: parent
            anchors.leftMargin: 75
            color: Qt.darker(theme.textColor, 1.2)
            font.pixelSize: 18
            font.bold: true
            anchors.topMargin: 10  // 从顶部下移30像素
            onTextChanged: {
                batchInfo.batchNo = text;
            }
        }
    }

    Row {
        id: rightRow
        spacing: 20
        anchors.verticalCenter: parent.verticalCenter
        anchors.right: parent.right
        anchors.rightMargin: 20

        Item{
            height:70
            width:70
            Image {
                id: volumeIcon
                source: "qrc:/assets/mute.png"
                anchors.verticalCenter: parent.verticalCenter
                visible:!buzzing
                MouseArea{
                    anchors.fill: parent
                    onClicked: {
                        buzzing = !buzzing;
                        collectionInfo.setBuzzing(buzzing);
                        operationInfo.insertOperationLog("打开蜂鸣","打开成功","")
                    }
                }
            }
            AnimatedImage {
                anchors.fill: parent
                anchors.topMargin: 20
                anchors.bottomMargin: 20
                anchors.rightMargin: 40
                anchors.leftMargin: 0
                anchors.verticalCenter: parent.verticalCenter
                source: "qrc:/assets/buzzing.gif"
                playing: true
                visible:buzzing
                onCurrentFrameChanged: {
                    // 检测是否播放到最后一帧
                    if (currentFrame === frameCount - 1) {
                        //currentFrame = 0
                        // infiniteGif.palying=true;
                    }
                }
                MouseArea{
                    anchors.fill: parent
                    onClicked: {
                        buzzing = !buzzing;
                        collectionInfo.setBuzzing(buzzing);
                        operationInfo.insertOperationLog("关闭蜂鸣","关闭成功","")
                    }
                }
            }
        }

        Item {
            id: timeContainer
            width: timeText.implicitWidth + 20
            height: 35
            anchors.verticalCenter: parent.verticalCenter

            Text {
                id: timeText
                text: Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
                color: Qt.darker(theme.textColor, 1.2)
                font.pixelSize: 20
                verticalAlignment: Text.AlignVCenter
                anchors.centerIn: parent
                anchors.leftMargin: 20
            }

            Timer {
                interval: 1000
                running: true
                repeat: true
                onTriggered: timeText.text = Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
            }
        }

        ComboBox {
            id: userComboBox
            width: 200
            height: 40
            model:  ["修改密码","退出登录"]
            currentIndex: 0
            anchors.verticalCenter: parent.verticalCenter
            displayText: getUserRole(userInfo.currentLogin)

            background: Rectangle {
                width: parent.width
                height: parent.height
                color: theme.secondaryColor
                radius: 10
            }

            contentItem: Row {
                spacing: 8
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 15

                Image {
                    source: "qrc:/assets/user@2x.png"
                    width: 25
                    height: 25
                    fillMode: Image.PreserveAspectFit
                    anchors.verticalCenter: parent.verticalCenter
                }

                Text {
                    text: userComboBox.displayText
                    color: Qt.darker(theme.textColor, 1.2)
                    font.pixelSize: 20
                    verticalAlignment: Text.AlignVCenter
                    elide: Text.ElideRight
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

            indicator: Item { }

            delegate: ItemDelegate {
                width: parent.width
                contentItem: Row {
                    spacing: 10
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                    anchors.leftMargin: 15

                    Image {
                        width: 22
                        height: 22
                        fillMode: Image.PreserveAspectFit
                        anchors.verticalCenter: parent.verticalCenter
                        source: index === 0
                                ? (userComboBox.highlightedIndex === index
                                   ? "qrc:/assets/changgepw_color.png"
                                   : "qrc:/assets/changepw.png")
                                : (userComboBox.highlightedIndex === index
                                   ? "qrc:/assets/logout_color.png"
                                   : "qrc:/assets/logout.png")
                    }

                    Text {
                        text: modelData
                        color: userComboBox.highlightedIndex === index ? "#1E90FF" : "#000000"
                        font.pixelSize: 20
                        verticalAlignment: Text.AlignVCenter
                    }
                }
                highlighted: userComboBox.highlightedIndex === index
                background: Rectangle {
                    color: highlighted ? "#E6F0FF" : "transparent"
                    radius: 10
                }
            }

            popup: Popup {
                y: userComboBox.height
                width: userComboBox.width
                implicitHeight: contentItem.implicitHeight + 10
                padding: 5

                background: Rectangle {
                    color: "white"
                    radius: 10
                }

                contentItem: ListView {
                    clip: true
                    implicitHeight: contentHeight
                    model: userComboBox.popup.visible ? userComboBox.delegateModel : null
                    currentIndex: userComboBox.highlightedIndex
                }
            }

            Text {
                id: arrowText
                text: "\uf104"
                font.family: iconFont.name
                color: "white"
                font.pixelSize: 16
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                anchors.rightMargin: 10
                rotation: userComboBox.popup.visible ? 90 : -90

                Behavior on rotation {
                    RotationAnimation { duration: 250; easing.type: Easing.InOutQuad }
                }
            }

            onActivated: function(index) {
                if (index === 1) {
                    var timestamp = Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss")
                    menuList.currentIndex = 0
                    currentPage = "main";
                    menuList.positionViewAtBeginning();
                    // 直接显示登录弹窗（无需通过 StackView）
                    loginPage.item.resetForm()
                    loginPage.item.visible = true
                    console.log("[" + timestamp + "] 已打开登录弹窗")
                }
                if (index ===0){
                    console.log("修改密码")
                    modifyPasswordPage.item.resetForm()
                    modifyPasswordPage.item.visible = true
                }
            }
        }

        Rectangle {
            id: closeBtn
            width: 35
            height: 35
            color: Qt.lighter(theme.secondaryColor, 1.4)
            radius: 17
            anchors.verticalCenter: parent.verticalCenter
            Image {
                source: "qrc:/assets/shutdown@2x.png"
                width: 25
                height: 25
                fillMode: Image.PreserveAspectFit
                anchors.centerIn: parent
            }

            MouseArea {
                anchors.fill: parent
                onClicked: Qt.quit()
            }
        }
    }
}

// === 页面切换：Loader方案 ===
property string currentPage: "main"

Item {
    id: pageContainer
    anchors {
        left: sideBar.right
        top: header.bottom
        right: parent.right
        bottom: parent.bottom
        leftMargin: 20
        topMargin: 10
        rightMargin: 10
        bottomMargin: 10
    }

    C.ZLoaderAnimation {
        id: mainPage
        source: "qrc:/pages/MainPage.qml"
        visible: currentPage === "main"
        onLoaded: {
            if (mainPage.item) {
                mainPage.item.goToPage = function(page) {
                    currentPage = page
                    var idx = -1
                    for (var i = 0; i < menuModel.count; i++) {
                        var el = menuModel.get(i)
                        if (el.pageId === page) { idx = i; break }
                    }
                    if (idx !== -1) {
                        menuList.currentIndex = idx
                        menuList.positionViewAtIndex(idx, ListView.Center)
                    }
                }
            }
        }
    }
    C.ZLoaderAnimation { id: alarmPage; source: "qrc:/pages/AlarmPage.qml";visible: currentPage === "alarm" }
    C.ZLoaderAnimation  { id: stirPage; source: "qrc:/pages/StirPage.qml";  visible: currentPage === "stir" }
    C.ZLoaderAnimation  { id: weighPage; source: "qrc:/pages/WeighPage.qml";  visible: currentPage === "weigh" }
    C.ZLoaderAnimation  { id: tempPage; source: "qrc:/pages/TempPage.qml";  visible: currentPage === "temp" }
    C.ZLoaderAnimation  { id: phPage; source: "qrc:/pages/PhPage.qml";  visible: currentPage === "ph" }
    C.ZLoaderAnimation  { id: condPage; source: "qrc:/pages/ConductivityPage.qml";  visible: currentPage === "conductivity" }
    C.ZLoaderAnimation  { id: chartPage; source: "qrc:/pages/ChartPage.qml";  visible: currentPage === "chart" }
    C.ZLoaderAnimation  { id: logPage; source: "qrc:/pages/LogPage.qml";  visible: currentPage === "log" }
    C.ZLoaderAnimation  { id: auditPage; source: "qrc:/pages/AuditPage.qml";  visible: currentPage === "audit" }
    C.ZLoaderAnimation  { id: settingPage; source: "qrc:/pages/SettingManagementPage.qml";  visible: currentPage === "setting" }
    C.ZLoaderAnimation  { id: aboutPage; source: "qrc:/pages/AboutPage.qml";  visible: currentPage === "about" }
    C.ZLoaderAnimation  { id: userPage; source: "qrc:/pages/UserManagementPage.qml";  visible: currentPage === "user" }
    C.ZLoaderAnimation  { id: batchPage; source: "qrc:/pages/BatchManagementPage.qml";  visible: currentPage === "batch" }
    C.ZLoaderAnimation  { id: testPage; source: "qrc:/pages/TestPage.qml";  visible: currentPage === "test" }
    C.ZLoaderAnimation  { id: testView; source: "qrc:/pages/TestView.qml";  visible: currentPage === "testView" }
}

property bool sideBarCollapsed: false

Rectangle {
    id: sideBarToggle
    width: 70
    height: 45
    color: theme.textColor
    radius: 20
    anchors.top: sideBar.top
    anchors.left: sideBar.right
    anchors.topMargin: 20
    anchors.leftMargin: -15
    border.width: 1
    border.color: "#2c3e507f"

    Text {
        id: toggleIcon
        text: "\uf104"
        font.family: iconFont.name
        font.pixelSize: 26
        color: theme.focusColor
        anchors.right: parent.right
        anchors.rightMargin: 14
        anchors.verticalCenter: parent.verticalCenter
        rotation: sideBarCollapsed ? 180 : 0

        Behavior on rotation { RotationAnimation { duration: 500; easing.type: Easing.OutCubic } }
    }

    MouseArea {
        anchors.fill: parent
        onClicked: sideBarCollapsed = !sideBarCollapsed
    }
}

Rectangle {
    id: sideBar
    width: sideBarCollapsed ? 0 : 120
    height: parent.height - 120
    color: "#2F3C4E"
    radius: 10
    clip: true
    anchors.left: parent.left
    anchors.top: header.bottom
    anchors.topMargin: 40
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 40
    anchors.leftMargin: sideBarCollapsed ? -10 : 20

    Behavior on width { NumberAnimation { duration: 500; easing.type: Easing.OutCubic } }


    ListView {
        id: menuList
        anchors.fill: parent
        anchors.margins: 20
        spacing: 10
        interactive: true
        boundsBehavior: Flickable.StopAtBounds
        model: menuModel
        currentIndex: 0
        visible: !sideBarCollapsed
        enabled: !sideBarCollapsed

        delegate: Rectangle {
            id: delegateItem
            width: menuList.width
            height: 90
            color: "transparent"
            radius: 12
            scale: index === menuList.currentIndex ? 1.02 : 1.0

            Behavior on scale { NumberAnimation { duration: 300; easing.type: Easing.OutCubic } }

            Column {
                anchors.centerIn: parent
                spacing: 0

                Item {
                    width: 90
                    height: 90
                    anchors.horizontalCenter: parent.horizontalCenter
                    Rectangle {
                        anchors.fill: parent
                        radius: 12
                        visible: mouseArea.containsMouse || index === menuList.currentIndex
                        color: mouseArea.containsMouse ? "#3A475A" : (index === menuList.currentIndex ? "#5D78A0" : "transparent")
                    }
                    Image {
                        id: iconImg
                        source: sidebarIconSource(name, mouseArea.containsMouse || index === menuList.currentIndex)
                        visible: source !== ""
                        width: index === menuList.currentIndex ? 42 : 38
                        height: width
                        fillMode: Image.PreserveAspectFit
                        anchors.top: parent.top
                        anchors.topMargin: 12
                        anchors.horizontalCenter: parent.horizontalCenter
                        smooth: true
                    }
                    Text {
                        visible: !iconImg.visible
                        text: icon
                        font.family: iconFont.name
                        font.pixelSize: index === menuList.currentIndex ? 39 : 36
                        color: (mouseArea.containsMouse || index === menuList.currentIndex) ? "white" : Qt.darker(theme.textColor, 1.2)
                        anchors.top: parent.top
                        anchors.topMargin: 12
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                    Text {
                        text: name
                        font.pixelSize: index === menuList.currentIndex ? 18 : 16
                        color: (mouseArea.containsMouse || index === menuList.currentIndex) ? "white" : Qt.darker(theme.textColor, 1.2)
                        anchors.bottom: parent.bottom
                        anchors.bottomMargin: 10
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                }
            }

            MouseArea {
                id: mouseArea
                anchors.fill: parent
                hoverEnabled: true
                enabled: true
                cursorShape: Qt.PointingHandCursor
                onClicked: {
                    menuList.currentIndex = index
                    currentPage = pageId
                    console.log("选中菜单：" + name + "，切换到页面：" + pageId)
                }
            }
        }

        ListModel {
            id: permissionModel
            ListElement { name: "主界面"; icon: "\uf015"; pageId: "main"; permission: 3 }
            ListElement { name: "用户管理"; icon: "\uf007"; pageId: "user"; permission: 0 }
            ListElement { name: "批号结果"; icon: "\uf007"; pageId: "batch"; permission: 0 }
            ListElement { name: "设置"; icon: "\uf013"; pageId: "setting"; permission: 1 }
            ListElement { name: "报警"; icon: "\uf071"; pageId: "alarm"; permission: 3 }
            ListElement { name: "测试page"; icon: "\uf007"; pageId: "testView"; permission: 3 }
            ListElement { name: "测试"; icon: "\uf007"; pageId: "test"; permission: 3 }
            ListElement { name: "搅拌"; icon: "\uf863"; pageId: "stir"; permission: 3 }
            ListElement { name: "称重"; icon: "\uf516"; pageId: "weigh"; permission: 3 }
            ListElement { name: "温度"; icon: "\uf2c7"; pageId: "temp"; permission: 3 }
            ListElement { name: "pH"; icon: "\uf0c3"; pageId: "ph"; permission: 3 }
            ListElement { name: "电导"; icon: "\uf0e7"; pageId: "conductivity"; permission: 3 }
            ListElement { name: "图表"; icon: "\uf080"; pageId: "chart"; permission: 3 }
            ListElement { name: "设备日志"; icon: "\uf15c"; pageId: "log"; permission: 3 }
            ListElement { name: "报警日志"; icon: "\uf14a"; pageId: "audit"; permission: 3 }
            ListElement { name: "关于"; icon: "\uf05a"; pageId: "about"; permission: 3 }
        }

        ListModel {
            id: menuModel
            ListElement { name: "主界面"; icon: "\uf015"; pageId: "main"; permission: 3 }
            ListElement { name: "用户管理"; icon: "\uf007"; pageId: "user"; permission: 0 }
            ListElement { name: "批号结果"; icon: "\uf007"; pageId: "batch"; permission: 0 }
            ListElement { name: "设置"; icon: "\uf013"; pageId: "setting"; permission: 1 }
            ListElement { name: "报警"; icon: "\uf071"; pageId: "alarm"; permission: 3 }
            ListElement { name: "测试page"; icon: "\uf007"; pageId: "testView"; permission: 3 }
            ListElement { name: "测试"; icon: "\uf007"; pageId: "test"; permission: 3 }
            ListElement { name: "搅拌"; icon: "\uf863"; pageId: "stir"; permission: 3 }
            ListElement { name: "称重"; icon: "\uf516"; pageId: "weigh"; permission: 3 }
            ListElement { name: "温度"; icon: "\uf2c7"; pageId: "temp"; permission: 3 }
            ListElement { name: "pH"; icon: "\uf0c3"; pageId: "ph"; permission: 3 }
            ListElement { name: "电导"; icon: "\uf0e7"; pageId: "conductivity"; permission: 3 }
            ListElement { name: "图表"; icon: "\uf080"; pageId: "chart"; permission: 3 }
            ListElement { name: "设备日志"; icon: "\uf15c"; pageId: "log"; permission: 3 }
            ListElement { name: "报警日志"; icon: "\uf14a"; pageId: "audit"; permission: 3 }
            ListElement { name: "关于"; icon: "\uf05a"; pageId: "about"; permission: 3 }
        }
    }
}

// 顶层登录遮罩，覆盖整个窗口
Loader {
    id: loginPage
    source: "qrc:/pages/LoginPage.qml"
    // anchors.fill: parent
}
Loader {
    id: modifyPasswordPage
    source: "qrc:/pages/ModifyPasswordPage.qml"
}

Loader{
    id: infoPage
    source:"qrc:/pages/InfoPage.qml"
}

Loader{
    id: emergencyPage
    source:"qrc:/pages/EmergencyPage.qml"
}
// 启动欢迎图遮罩，覆盖整个窗口，3秒后自动消失，点击取消
Rectangle {
    id: welcomeOverlay
    anchors.fill: parent
    color: "black"
    visible: true
    z: 200

    Image {
        anchors.fill: parent
        source: "qrc:/assets/welcome.png"
        fillMode: Image.PreserveAspectCrop
        smooth: true
    }

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.AllButtons
        onClicked: welcomeOverlay.visible = false
    }

    Timer {
        interval: 2000
        running: true
        repeat: false
        onTriggered: welcomeOverlay.visible = false
    }
}


function updateMenuByRoleId(userRole) {
    menuModel.clear()
    console.log("permission>>>>")
    for (var i = 0; i < permissionModel.count; i++) {
        var item = permissionModel.get(i)
        if (item.permission >= userRole) {
            menuModel.append({
                name: item.name,
                icon: item.icon,
                pageId: item.pageId
            })
        }
    }
}

function getUserRole(loginUser){
    if (loginUser.name === undefined) return "";
    var r=loginUser.name;
    var role = Global.permissionLabel(loginUser.permission)

    r += ":" + role;
    return r;
}

function sidebarIconSource(name, active) {
    var base = "qrc:/assets/sidebar/";
    switch (name) {
    case "主界面": return base + (active ? "home_white.png" : "home_selected.png");
    case "用户管理": return base + (active ? "user_management_white.png" : "user_management_selected.png");
    case "批号结果": return base + (active ? "batch_result_white.png" : "batch_result_selected.png");
    case "设置": return base + (active ? "settings_white.png" : "settings_selected.png");
    case "报警": return base + (active ? "alarm_white.png" : "alarm_selected.png");
    case "搅拌": return base + (active ? "stir_white.png" : "stir_selected.png");
    case "测试page": return base + (active ? "stir_white.png" : "stir_selected.png");
    case "测试": return base + (active ? "stir_white.png" : "stir_selected.png");
    case "称重": return base + (active ? "weight_white.png" : "weight_selected.png");
    case "温度": return base + (active ? "temperature_white.png" : "temperature_selected.png");
    case "pH": return base + (active ? "ph_white.png" : "ph_selected.png");
    case "电导": return base + (active ? "conductivity_white.png" : "conductivity_selected.png");
    case "图表": return base + (active ? "charts_white.png" : "charts_selected.png");
    case "设备日志": return base + (active ? "device_logs_white.png" : "device_logs_selected.png");
    case "报警日志": return base + (active ? "audit_white.png" : "audit_selected.png");
    case "自动化": return base + (active ? "automation_white.png" : "automation_selected.png");
    case "关于": return base + (active ? "about_white.png" : "about_selected.png");
    default: return "";
    }
}
}
